package cn.murky.admin.filter;

import cn.murky.admin.core.utils.SecurityUtils;
import cn.murky.core.exception.MurkyException;
import cn.murky.security.entity.SecurityUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.smartboot.http.common.utils.AntPathMatcher;

import java.util.List;
import java.util.SortedMap;

@Component(index = 1)
@Slf4j
public class AdminFilter implements Filter {
    @Inject("${security.path-ignore}")
    private List<String> ignoreList;

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        SecurityUserInfo userInfo = null;

        long count = ignoreList.stream().filter(path -> new AntPathMatcher().match(path,ctx.uri().getPath())).count();
        if (count == 0) {
            userInfo = SecurityUtils.getUserInfo();
        }

        SecurityUtils.runnable(userInfo, () -> {
            try {
                chain.doFilter(ctx);
            } catch (Throwable e) {
                throw new MurkyException(e);
            }
        });
    }
}
